package com.yonyou.ucf.mdf.app.isvdxq.other.controller;

import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.yonyou.ucf.mdf.app.isvdxq.ReturnResult.DataResult;
import com.yonyou.ucf.mdf.app.isvdxq.common.DxqConfig;
import com.yonyou.ucf.mdf.app.isvdxq.common.NoNeedToken;
import com.yonyou.ucf.mdf.app.isvdxq.firstpart.device.entity.DeviceListEntity;
import com.yonyou.ucf.mdf.app.isvdxq.firstpart.device.service.DeviceListService;
import com.yonyou.ucf.mdf.app.isvdxq.other.entity.OrgUnitEntity;
import com.yonyou.ucf.mdf.app.isvdxq.other.entity.SuiteauthEntity;
import com.yonyou.ucf.mdf.app.isvdxq.other.entity.UserstaffEntity;
import com.yonyou.ucf.mdf.app.isvdxq.other.entity.WarehouseEntity;
import com.yonyou.ucf.mdf.app.isvdxq.other.model.AccessTokenResponse;
import com.yonyou.ucf.mdf.app.isvdxq.other.model.DcUrlResult;
import com.yonyou.ucf.mdf.app.isvdxq.other.model.TenantViewBean;
import com.yonyou.ucf.mdf.app.isvdxq.other.model.UserBean;
import com.yonyou.ucf.mdf.app.isvdxq.other.service.*;
import com.yonyou.ucf.mdf.app.isvdxq.utils.*;
import lombok.SneakyThrows;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

//@RestController=@Controller+@ResposeBody,返回JSON字符串。但不能解析html或jsp视图，不能返回jsp和html页面

/**
 *
 */
@RestController
@RequestMapping(value = {DxqConfig.pre_apiUrl+"/public",DxqConfig.pre_pcUrl+"/public"})
public class PublicController {
    private static final Logger logger = LoggerFactory.getLogger(PublicController.class);

    @Autowired
    private BaseService baseService;

    @Autowired
    private UserstaffService userstaffService;
    @Autowired
    private WarehouseService warehouseService;
    @Autowired
    private OrgUnitService orgUnitService;

    @Autowired
    private SuiteauthService suiteauthService;

    @Autowired
    private DeviceListService deviceListService;

    @Autowired
    private MyTokenService myTokenService;

    /**
     * 获取数据中心地址
     *
     * @return
     * @throws IOException
     */
    @NoNeedToken
    @GetMapping("/getGatewayAddress")
    public DataResult getGatewayAddress(HttpServletRequest request) {
        DataResult result = new DataResult(0, "操作失败");
        String tenantId = baseService.getTenantId(request);
        try {
            DcUrlResult dcUrl = myTokenService.getGateway(tenantId);
            result = new DataResult(1, "操作成功");
            result.setData(dcUrl);
            // 获取租户名称
            String tenantInfo = myTokenService.getTenantById(tenantId);
            if (StringUtils.isNotBlank(tenantInfo)) {
                JSONObject object = JSONObject.parseObject(tenantInfo);
                result.setInfo(object.getJSONObject("tenant").get("tenantName"));
            }
        } catch (Exception ex) {
            result.setMessage(ex.getMessage());
        }
        return result;
    }

    /**
     * 获取当前环境
     *
     * @return
     */
    @NoNeedToken
    @GetMapping("/getEnvActive")
    public Object getEnvActive() {
        try {
            String env = PropertyUtil.getPropertyByKey("spring.profiles.active", "false");
            String apiUrl = PropertyUtil.getPropertyByKey("runtime.server.url", "");
            boolean enableNativeQuery = BooleanUtils.toBoolean(env);
            HashMap<String, String> hashMap = new HashMap<>();
            hashMap.put("env", env);
            hashMap.put("apiUrl", String.format("%s%s", apiUrl, DxqConfig.pre_apiUrl));
            String logtxt = JSONObject.toJSONString(hashMap);
            return logtxt;
        } catch (Exception var13) {
            return null;
        }
    }

    /**
     * 查询当前运行环境
     * @param key
     * @return
     */
    @NoNeedToken
    @GetMapping("/getEnvByKey")
    public Object getEnvByKey(@RequestParam(required = false) String key) {
        if (StringUtils.isEmpty(key)) key = "spring.profiles.active";
        String result = myTokenService.getProperty(key);
        return result;
    }

    /**
     * PC 跳转获取用户信息方案
     * todo 暂未使用
     * @return
     * @throws IOException
     */
    @NoNeedToken
    @GetMapping("/getUserInfoByYhtToken")
    public DataResult getUserInfoByYhtToken() throws IOException {
        DataResult result = new DataResult(1, "操作成功");
        Map<String, Object> userInfoByYhtToken = myTokenService.getUserInfoByYhtToken();
        result.setData(userInfoByYhtToken);
        return result;
    }

    /**
     * 租户Id 获取Token /apidxq/isv2/public/getAccessToken?tenant_id=
     * todo 测试是否等同 /isv/suite/getAccessToken/V2?tenantId=
     * @param tenantId
     * @return
     */
    @NoNeedToken
    @SneakyThrows
    @RequestMapping("/getAccessToken")
    public DataResult getAccessToken(@RequestParam(value = "tenant_id", required = false,
            defaultValue = "") String tenantId, @RequestParam(value = "access_token", required = false,
            defaultValue = "") String access_token, HttpServletRequest request) {
        DataResult result = new DataResult(998, "登录过期");
        AccessTokenResponse res = new AccessTokenResponse();
        logger.info("[getAccessToken]" + tenantId);
        try {
            String userId = RequestTool.getHeaderAndParameter(request, DxqConfig.DXQ_userId);
            res = baseService.getAccessToken3(tenantId);
            if (StringUtils.isEmpty(access_token)) {
                result = new DataResult(1, "操作成功");
                result.setData(res);
                return result;
            }
            // 更新本地token
            SuiteauthEntity entity = suiteauthService.CheckEntityByToken(access_token);
            if (entity != null) {
                // 到期时间差 单位秒
                long diffTime = MyTool.timeDiff(entity.getPubts(),
                        MyTool.GenerateTime("yyyy-MM-dd HH:mm:ss"),
                        "yyyy-MM-dd HH:mm:ss") / 1000;
                // 超时30分钟 提示重新登录
                int refreshTime = (entity.getRefreshTime() == null || entity.getRefreshTime() == 0) ? 1800 : entity.getRefreshTime().intValue();
                if (Long.parseLong(entity.getExpireAt()) < diffTime - refreshTime) {
                    entity.setAccessToken(res.getAccessToken());
                    entity.setExpireAt(String.valueOf(res.getExpire()));
                    entity.setUserid(userId);
                    entity.setRefreshTime(refreshTime);
                    entity.setDxqToken(MyTool.GenerateDxqToken(tenantId));
                    suiteauthService.UpdateEntity(entity);
                    logger.info("[getAccessToken]本地更新" + new Gson().toJson(res));
                }
            }
            result = new DataResult(1, "操作成功");
            result.setData(res);
        } catch (Exception ex) {
            logger.info("[getAccessToken]" + ex.getMessage());
        }

        return result;
    }

    /**
     * 配置更新 登录成功默认更新
     * 更新租户信息 并记录最后登录人
     * @param tenantId
     * @param request
     */
    private void UpdateSuiteConfig(String tenantId, String yhtUserId, HttpServletRequest request) {
        try {
            AccessTokenResponse resToken = baseService.getAccessToken3(tenantId);
            SuiteauthEntity suiteauthEntity = suiteauthService.CheckEntityByKey(tenantId, DxqConfig.appKey);
            // 获取租户名称
            String todayString = MyTool.GenerateTime("yyyy-MM-dd");
            String tenantName = "";
            if (suiteauthEntity != null) {
                suiteauthEntity.setDxqToken(MyTool.GenerateDxqToken(tenantId));
                suiteauthEntity.setAccessToken(resToken.getAccessToken());
                suiteauthEntity.setExpireAt(String.valueOf(resToken.getExpire()));
                suiteauthEntity.setUserid(yhtUserId);
                suiteauthEntity.setEditTime(todayString);
                String tenantInfo = myTokenService.getTenantById(tenantId);
                if (StringUtils.isNotBlank(tenantInfo)) {
                    JSONObject object = JSONObject.parseObject(tenantInfo);
                    tenantName = object.getJSONObject("tenant").get("tenantName").toString();
                }
                suiteauthEntity.setTenantName(tenantName);
                suiteauthService.UpdateEntity(suiteauthEntity);
            }
        } catch (Exception ex) {
            System.out.println(ex.getMessage());
        }
    }

    /**
     * getAccessTokenCustom?access_token=&tenant_id=
     * 默认tenantId 私有Token换取公有Token
     */
    @RequestMapping("/getAccessTokenCustom")
    public DataResult getAccessTokenCustom(HttpServletRequest request, @RequestParam(value = "tenant_id", required = false,
            defaultValue = "") String tenantId) {
        DataResult<AccessTokenResponse> res = new DataResult<>(0, "操作失败");
        String access_token = RequestTool.getHeaderAndParameter(request, DxqConfig.DXQ_ACCESS_TOKEN);
        AccessTokenResponse resToken = new AccessTokenResponse();
        if (StringUtils.isBlank(tenantId)) tenantId = DxqConfig.tenantId;
        try {
            boolean flagNext = MyTool.checkToken(access_token, tenantId);
            if (!flagNext) return res;
            resToken = baseService.getAccessToken3(tenantId);
            String keySafe = Base64Util.Base64ToString(access_token,6);
            // 验证旧Token是否存在
            SuiteauthEntity entity = suiteauthService.CheckEntityByToken(keySafe, true);
            if (entity != null) {
                entity.setAccessToken(resToken.getAccessToken());
                entity.setExpireAt(String.valueOf(resToken.getExpire()));
                suiteauthService.UpdateEntity(entity);
            }
            res.setStatus(1);
            res.setMessage("操作成功");
            res.setData(resToken);
        } catch (Exception ex) {
            logger.info(ex.getMessage());
            res.setMessage(ex.getMessage());
        }
        return res;
    }

    /** 方案一：
     * 获取租户列表 查询职员表数据 本地维护手持设备登录密码职员表等同 手持设备用户表
     * 租户数据来源本地添加或者三方推送；数据添加时，同时添加职员信息，并更新租户表信息
     * 前台录入手机号，加载租户列表，选择并录入登录密码，确认登录
     * 方案二：
     * 用友原生页面获取 appcode 换取 tenantId 有值即为安全
     * 本地免密登录：tenantId 换取 accessToken； 抓取手机号、抓取录入密码本地职员表记录登录信息。
     * 后台定时同步用户数据信息，用于数据留档；
     * @param userName
     * @param request
     * @return
     */
    @NoNeedToken
    @RequestMapping("/getTenantList")
    public DataResult getTenantList(String userName, HttpServletRequest request) {
        DataResult resObj = new DataResult<>();
        if (StringUtils.isEmpty(userName)) return resObj;
        try {
            List<UserstaffEntity> userstaffEntities = userstaffService.SelectAllByMobile(userName);
            resObj = new DataResult<>(1, "操作成功");
            List<TenantViewBean> dataList = new ArrayList<>();
            List<UserstaffEntity> collect = userstaffEntities.stream().collect(Collectors.toList());
            for (UserstaffEntity item : collect) {
                TenantViewBean tenantViewBean = new TenantViewBean();
                tenantViewBean.setTenant_id(item.getTenant_id());
                tenantViewBean.setTenantName(item.getTenantName());
                dataList.add(tenantViewBean);
            }
            resObj.setData(dataList);
            resObj.setTotalSize(dataList.size());
        } catch (Exception ex) {
            resObj.setMessage(ex.getMessage());
            String res = JSONObject.toJSONString(resObj);
            logger.error(res);
        }
        return resObj;
    }

    /**
     * 更新租户配置
     * 租户关联 配置中心数据自动更新
     * @param collect
     * @return
     */
    private List<TenantViewBean> autoTenantListConfig(List<UserstaffEntity> collect) {
        List<TenantViewBean> dataList = new ArrayList<>();
        try {
            String todayString = MyTool.GenerateTime("yyyy-MM-dd");
            List<String> tids = collect.stream().map(it -> it.getTenant_id()).distinct().collect(Collectors.toList());
            List<SuiteauthEntity> suiteauthEntities = suiteauthService.SelectByTenantIds(tids);
            for (UserstaffEntity item : collect) {
                TenantViewBean tenantViewBean = new TenantViewBean();
                tenantViewBean.setTenant_id(item.getTenant_id());
                tenantViewBean.setTenantName(item.getTenantName());
                SuiteauthEntity entity = suiteauthEntities.stream().filter(it -> it.getTenant_id().equals(item.getTenant_id()))
                        .findFirst().orElse(null);
                if (entity != null || todayString != entity.getEditTime()) {
                    // 获取租户名称
                    String tenantInfo = myTokenService.getTenantById(item.getTenant_id());
                    if (StringUtils.isNotBlank(tenantInfo)) {
                        JSONObject object = JSONObject.parseObject(tenantInfo);
                        String tenantName = object.getJSONObject("tenant").get("tenantName").toString();
                        tenantViewBean.setTenantName(tenantName);
                        entity.setTenantName(tenantName);
                        entity.setEditTime(todayString);
                        //更新租户名称
                        item.setTenantName(tenantName);
                        suiteauthService.UpdateEntity(entity);
                        userstaffService.UpdateEntity(item);
                    }
                }
                dataList.add(tenantViewBean);
            }
        } catch (Exception ex) {
            String res = JSONObject.toJSONString(ex.getMessage());
            logger.error(res);
        }
        return dataList;
    }

    /**
     * 验证设备是否注册
     * @param devicetag
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping("/devicecheck")
    public DataResult getDeviceCheck(String devicetag, HttpServletRequest request) throws Exception {
        return  checkDevice(devicetag, request);
    }

    private DataResult checkDevice(String devicetag, HttpServletRequest request) {
        DataResult<UserBean> resObj = new DataResult<>();
        try {
            String tenantId = baseService.getTenantId(request);
            if (StringUtils.isBlank(tenantId)) {
                resObj.setMessage("租户信息不能为空");
                return resObj;
            }
            //mac地址不为空时，验证设备mac授权
            if (StringUtils.isEmpty(devicetag)) {
                resObj = new DataResult<>(0, "设备标识异常");
                return resObj;
            }

            if (devicetag.contains("%")) devicetag = URLDecoder.decode(devicetag, "utf-8");
            DeviceListEntity deviceListEntity = deviceListService.SelectEntityByKey(tenantId, devicetag);
            if (deviceListEntity == null) {
                // 新增数据
                deviceListService.InsertEntity(5, devicetag, tenantId);
                resObj.setMessage("设备未登记");
                return resObj;
            } else if (deviceListEntity.getStatus() == 0) {
                resObj.setMessage("设备已登记, 未审批");
                return resObj;
            }

            resObj.setStatus(1);
            resObj.setMessage("设备验证通过");
        } catch (Exception ex) {
            resObj.setMessage(ex.getMessage());
            String res = JSONObject.toJSONString(resObj);
            logger.error(res);
        }
        return resObj;
    }

    /**
     * 用户登录 无Token，TenantId查询赋值
     * devicetag imei\mac\ip
     * @param userName
     * @param password
     * @param request
     * @return
     * @throws Exception
     */
    @NoNeedToken
    @SneakyThrows
    @RequestMapping("/logincheck")
    public DataResult getLoginCheck(String userName, String password, @RequestParam(required = false, defaultValue = "") String devicetag, HttpServletRequest request) throws Exception {
        if (DxqConfig.DXQ_sandbox.equals(DxqConfig.active)) {
            return LoginCheckLocal(userName, password, devicetag, request);
        } else {
            return LoginCheck(userName, password, devicetag, request);
        }
    }

    @SneakyThrows
    private DataResult LoginCheckLocal(String userName, String password, @RequestParam(required = false, defaultValue = "") String devicetag, HttpServletRequest request){
        DataResult<UserBean> resObj = new DataResult<>();
        String tenantId = baseService.getTenantId(request);
        String userId = RequestTool.getHeaderAndParameter(request, DxqConfig.DXQ_userId);
        Map<String, String> params = RequestTool.getParams(request);

        if (StringUtils.isBlank(tenantId)) {
            resObj.setMessage("租户信息不能为空");
            return resObj;
        }
        // 支持header query传参
        if (StringUtils.isEmpty(devicetag) && params.containsKey("devicetag")) {
            devicetag = params.get("devicetag"); //设备标识
        }
        //mac地址不为空时，验证设备mac授权
        if (StringUtils.isNotEmpty(devicetag)) {
            if (devicetag.contains("%")) devicetag = URLDecoder.decode(devicetag, "utf-8");
            DeviceListEntity deviceListEntity = deviceListService.SelectEntityByKey(tenantId, devicetag);
            if (deviceListEntity == null) {
                // 新增数据
                deviceListService.InsertEntity(5, devicetag, tenantId);
                resObj.setMessage("设备未登记");
                return resObj;
            } else if (deviceListEntity.getStatus() == 0) {
                resObj.setMessage("设备已登记, 未审批");
                return resObj;
            }
        }
        //兼容 账号密码头文件
        if (StringUtils.isBlank(userName) && params.containsKey("userName")) {
            userName = params.get("userName").toString();
        }
        if (StringUtils.isBlank(password) && params.containsKey("password")) {
            password = params.get("password").toString();
        }
        if (StringUtils.isBlank(userName)) {
            resObj.setMessage("用户名不能为空");
            return resObj;
        }
        if (StringUtils.isBlank(password)) {
            resObj.setMessage("密码不能为空");
            return resObj;
        }
        // 获取用户信息
        String access_token = "";// 无Token tenantId查询赋值
        UserBean uInfo = baseService.getUserInfo(access_token,tenantId,userName);
        String moblie = PhoneFormatCheckUtils.isPhoneLegal(userName) ? userName : uInfo.getUserMobile();
        String safePw = DigestUtils.md5Hex(password);
        //查询更新本地用户表数据
        UserstaffEntity userstaffEntity = userstaffService.SelectByTenantKey(tenantId, uInfo.getUserId());
        if (userstaffEntity == null) {
            userstaffEntity = new UserstaffEntity();
            userstaffEntity.setId(Long.parseLong(MyTool.getRandomId()));
            userstaffEntity.setUserName(uInfo.getUserName());
            userstaffEntity.setYhtUserId(uInfo.getUserId());
            userstaffEntity.setMobile(moblie);
            userstaffEntity.setPassword(safePw);
            userstaffEntity.setTenant_id(tenantId);
            String tenantName = "";
            String tenantInfo = myTokenService.getTenantById(tenantId);
            if (StringUtils.isNotBlank(tenantInfo)) {
                JSONObject object = JSONObject.parseObject(tenantInfo);
                tenantName = object.getJSONObject("tenant").get("tenantName").toString();
            }
            userstaffEntity.setTenantName(tenantName);
            userstaffService.InsertEntity(userstaffEntity);
        } else if (!StringUtils.isEmpty(userstaffEntity.getPassword())) {
            if (!userstaffEntity.getPassword().equals(password) && !userstaffEntity.getPassword().equals(safePw)) {
                resObj.setMessage("登录密码错误");
                return resObj;
            }
        }
        if (userstaffEntity.getStatus() != 1) {
            resObj.setMessage("账户已锁定,请联系管理员");
            return resObj;
        } else {
            userstaffEntity.setMobile(moblie);
            userstaffEntity.setYhtUserId(uInfo.getUserId());
            userstaffEntity.setUserName(uInfo.getUserName());
            userstaffEntity.setTenant_id(tenantId);
            String tenantName = "";
            String tenantInfo = myTokenService.getTenantById(tenantId);
            if (StringUtils.isNotBlank(tenantInfo)) {
                JSONObject object = JSONObject.parseObject(tenantInfo);
                tenantName = object.getJSONObject("tenant").get("tenantName").toString();
            }
            userstaffEntity.setTenantName(tenantName);
            if (StringUtils.isEmpty(userstaffEntity.getPassword())) userstaffEntity.setPassword(safePw);
            else if (userstaffEntity.getPassword().equals(password)) userstaffEntity.setPassword(safePw);
            userstaffService.UpdateEntity(userstaffEntity);
        }
        //System.out.println(DigestUtils.md5Hex(password));
        uInfo.setName(userstaffEntity.getTenantName());
        uInfo.setUser_id(String.valueOf(userstaffEntity.getId()));
        uInfo.setTenant_id(userstaffEntity.getTenant_id());
        uInfo.setYyToken(access_token);
        String keySafe = Base64Util.ToBase64(MyTool.GenerateDxqToken(userstaffEntity.getTenant_id()),6);
        uInfo.setDxqToken(keySafe);
        resObj.setStatus(1);
        resObj.setMessage("操作成功");
        //根据yhtUserId 获取组织权限
        List<String> orgList = baseService.getOrgListByUserId(uInfo.getUserId(), tenantId);
        if (orgList.size() > 0) {
            List<OrgUnitEntity> myOrgList = orgUnitService.SelectByIds(orgList, tenantId);
            List<WarehouseEntity> warehouseList = warehouseService.SelectByOrgIds(orgList, tenantId);
            uInfo.setOrgids(myOrgList);
            uInfo.setWarehouseList(warehouseList);
        }
        resObj.setData(uInfo);
        DcUrlResult dcUrl = myTokenService.getGateway(tenantId);
        resObj.setInfo(dcUrl);
        return resObj;
    }

    private DataResult LoginCheck(String userName, String password, @RequestParam(required = false, defaultValue = "") String devicetag, HttpServletRequest request) {
        DataResult<UserBean> resObj = new DataResult<>();
        try {
            String tenantId = baseService.getTenantId(request);
            String userId = RequestTool.getHeaderAndParameter(request, DxqConfig.DXQ_userId);
            Map<String, String> params = RequestTool.getParams(request);
            if (StringUtils.isBlank(tenantId)) {
                resObj.setMessage("租户信息不能为空");
                return resObj;
            }
            // 支持header query传参
            if (StringUtils.isEmpty(devicetag) && params.containsKey("devicetag")) {
                devicetag = params.get("devicetag"); //设备标识
            }
            //mac地址不为空时，验证设备mac授权
            if (StringUtils.isNotEmpty(devicetag)) {
                if (devicetag.contains("%")) devicetag = URLDecoder.decode(devicetag, "utf-8");
                DeviceListEntity deviceListEntity = deviceListService.SelectEntityByKey(tenantId, devicetag);
                if (deviceListEntity == null) {
                    // 新增数据
                    deviceListService.InsertEntity(5, devicetag, tenantId);
                    resObj.setMessage("设备未登记");
                    return resObj;
                } else if (deviceListEntity.getStatus() == 0) {
                    resObj.setMessage("设备已登记, 未审批");
                    return resObj;
                }
            }
            //兼容 账号密码头文件
            if (StringUtils.isBlank(userName) && params.containsKey("userName")) {
                userName = params.get("userName").toString();
            }
            if (StringUtils.isBlank(password) && params.containsKey("password")) {
                password = params.get("password").toString();
            }
            if (StringUtils.isBlank(userName)) {
                resObj.setMessage("用户名不能为空");
                return resObj;
            }
            if (StringUtils.isBlank(password)) {
                resObj.setMessage("密码不能为空");
                return resObj;
            }

            // 获取用户信息
            String access_token = "";// 无Token tenantId查询赋值
            UserBean uInfo = baseService.getUserInfo(access_token,tenantId,userName);
            String moblie = PhoneFormatCheckUtils.isPhoneLegal(userName) ? userName : uInfo.getUserMobile();
            String safePw = DigestUtils.md5Hex(password);
            //查询更新本地用户表数据
            UserstaffEntity userstaffEntity = userstaffService.SelectByTenantKey(tenantId, uInfo.getUserId());
            if (userstaffEntity == null) {
                userstaffEntity = new UserstaffEntity();
                userstaffEntity.setId(Long.parseLong(MyTool.getRandomId()));
                userstaffEntity.setUserName(uInfo.getUserName());
                userstaffEntity.setYhtUserId(uInfo.getUserId());
                userstaffEntity.setMobile(moblie);
                userstaffEntity.setPassword(safePw);
                userstaffEntity.setTenant_id(tenantId);
                String tenantName = "";
                String tenantInfo = myTokenService.getTenantById(tenantId);
                if (StringUtils.isNotBlank(tenantInfo)) {
                    JSONObject object = JSONObject.parseObject(tenantInfo);
                    tenantName = object.getJSONObject("tenant").get("tenantName").toString();
                }
                userstaffEntity.setTenantName(tenantName);
                userstaffService.InsertEntity(userstaffEntity);
            } else if (!StringUtils.isEmpty(userstaffEntity.getPassword())) {
                if (!userstaffEntity.getPassword().equals(password) && !userstaffEntity.getPassword().equals(safePw)) {
                    resObj.setMessage("登录密码错误");
                    return resObj;
                }
            }
            if (userstaffEntity.getStatus() != 1) {
                resObj.setMessage("账户已锁定,请联系管理员");
                return resObj;
            } else {
                userstaffEntity.setMobile(moblie);
                userstaffEntity.setYhtUserId(uInfo.getUserId());
                userstaffEntity.setUserName(uInfo.getUserName());
                userstaffEntity.setTenant_id(tenantId);
                String tenantName = "";
                String tenantInfo = myTokenService.getTenantById(tenantId);
                if (StringUtils.isNotBlank(tenantInfo)) {
                    JSONObject object = JSONObject.parseObject(tenantInfo);
                    tenantName = object.getJSONObject("tenant").get("tenantName").toString();
                }
                userstaffEntity.setTenantName(tenantName);
                if (StringUtils.isEmpty(userstaffEntity.getPassword())) userstaffEntity.setPassword(safePw);
                else if (userstaffEntity.getPassword().equals(password)) userstaffEntity.setPassword(safePw);
                userstaffService.UpdateEntity(userstaffEntity);
            }

            //System.out.println(DigestUtils.md5Hex(password));
            uInfo.setName(userstaffEntity.getTenantName());
            uInfo.setUser_id(String.valueOf(userstaffEntity.getId()));
            uInfo.setTenant_id(userstaffEntity.getTenant_id());
            uInfo.setYyToken(access_token);
            String keySafe = Base64Util.ToBase64(MyTool.GenerateDxqToken(userstaffEntity.getTenant_id()),6);
            uInfo.setDxqToken(keySafe);
            resObj.setStatus(1);
            resObj.setMessage("操作成功");

            String res = JSONObject.toJSONString(resObj);
            logger.info(res);
            //根据yhtUserId 获取组织权限
            List<String> orgList = baseService.getOrgListByUserId(uInfo.getUserId(), tenantId);
            /*if (orgList.size() == 0) {
                resObj.setStatus(0);
                resObj.setMessage("无组织权限,请联系管理员！");
                resObj.setData(uInfo);
                return resObj;
            }*/
            if (orgList.size() > 0) {
                List<OrgUnitEntity> myOrgList = orgUnitService.SelectByIds(orgList, tenantId);
                List<WarehouseEntity> warehouseList = warehouseService.SelectByOrgIds(orgList, tenantId);
                uInfo.setOrgids(myOrgList);
                uInfo.setWarehouseList(warehouseList);
            }
            resObj.setData(uInfo);
            DcUrlResult dcUrl = myTokenService.getGateway(tenantId);
            resObj.setInfo(dcUrl);
            //UpdateSuiteConfig(tenantId, uInfo.getUserId(), request);
        } catch (Exception ex) {
            resObj.setMessage(ex.getMessage());
            String res = JSONObject.toJSONString(resObj);
            logger.error(res);
        }
        return resObj;
    }

    /**
     * 用户查询权限
     * @param userId
     * @param access_token
     * @param request
     * @return
     */
    @RequestMapping("/GetPermissionByUserId")
    public DataResult GetPermissionByUserId(String userId, String access_token, HttpServletRequest request) {
        DataResult res = new DataResult(0, "查询失败");
        System.out.println("用户查询权限参数:" + userId + "|" + access_token);
        try {
            String tenantId = baseService.getTenantId(request);
            if(StringUtils.isEmpty(userId)) {
                res.setMessage("用户参数异常");
                return res;
            }
            logger.info("用户查询权限tenantId:" + tenantId);
            // 本地验证
            String localcheck = request.getParameter("localcheck");
            if(!StringUtils.isEmpty(localcheck) && localcheck.equals("true")) {
                UserstaffEntity userstaffEntity = userstaffService.SelectByUserId(userId);
                if (userstaffEntity == null) {
                    res.setMessage("用户不存在");
                    return res;
                }
            }
            List<String> orgList = baseService.getOrgListByUserId(userId, tenantId);
            logger.info("用户查询权限tenantId:" + orgList);
            if (orgList.size() == 0) {
                res = new DataResult(0, "组织权限异常");
                return res;
            }
            Map<String, Object> userInfoByYhtToken = myTokenService.getUserInfoByYhtToken();
            // 本地组织过滤
            List<OrgUnitEntity> myOrgList = orgUnitService.SelectByIds(orgList, tenantId);
            List<WarehouseEntity> warehouseList = warehouseService.SelectByOrgIds(orgList, tenantId);
            HashMap<String, Object> map = new HashMap<String, Object>();
            map.put("userEntity", userInfoByYhtToken);
            map.put("orgList", orgList);
            map.put("warehouseList", warehouseList);
            res = new DataResult(1, "查询成功");
            res.setData(map);
        } catch (Exception ex) {
            res.setMessage(ex.getMessage());
            logger.info("[GetPermissionByUserId]" + ex.getMessage());
        }
        return res;
    }

    // 用户检测并更新租户Name,默认在线平台添加维护
    @RequestMapping("/getStaffList")
    public DataResult getStaffList(HttpServletRequest request) {
        DataResult result = new DataResult(0, "查询失败");
        try {
            String tenantId = baseService.getTenantId(request);
            String userId = RequestTool.getHeaderAndParameter(request, DxqConfig.DXQ_userId);
            Map<String, String> params = RequestTool.getParams(request);

            String moblie = params.get("mobile");
            String tenantName = params.get("tenantName");
            UserstaffEntity userstaffEntity = userstaffService.SelectByMobile(tenantId, moblie);
            result = new DataResult(1, "查询成功");
            if (userstaffEntity != null) {
                userstaffEntity.setTenantName(tenantName);
                userstaffEntity.setDr(0);
                result.setData(userstaffEntity);
                userstaffService.UpdateEntity(userstaffEntity);
            }
        } catch (Exception ex) {
            result.setMessage(ex.getMessage());
        }
        return result;
    }
}
